// pages/consultation/buyConsult/buyConsult.js
const app = getApp()
var help = require('../../../utils/help.js');
var login = require('../../../utils/login.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: app.data.imageUrl,
    showUpload: "",//赋值为active时页面元素显示
    type: 0,
    yisheng_id: 0,
    yisheng_data: {},
    msg: '',
    product_images: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.yisheng_id) {
      this.setData({
        yisheng_id: options.yisheng_id
      })
    }
    if (options.type) {
      this.setData({
        type: options.type
      })
    }
  },
  //支付
  payment:function(e){
    var that = this;
    var url = app.data.apiUrl + 'Zxorder/apply_sub';
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      yisheng_id: that.data.yisheng_id,
      type: that.data.type,
      msg: that.data.msg,
      images: that.data.product_images.join(',')
    };
    help.get(url, data, that, function (res, that) {
      var result = res.data;
      // console.log(result);
      if (result.code == 1) {
        that.goPay(result.data.pay_id);
      } else {
        help.msg(result.msg)
        return false;
      }

    });
  },
  /**
   * 微信支付
   */
  goPay: function (pay_id) {
    var that = this;
    var url = app.data.apiUrl + '/Zxorder/wxpay';
    wx.showLoading({
      title: '正在加载...',
    })
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      pay_id: pay_id,
    };
    help.get(url, data, that, function (res, that) {
      wx.hideLoading()
      var result = res.data;
      console.log(result);
      if (result.code == 1) {
        var url = '/pages/consultation/quiz/quiz?id=' + pay_id;
        // help.goUrl(url);
        wx.requestPayment({
          'timeStamp': result.data.timeStamp,
          'nonceStr': result.data.nonceStr,
          'package': result.data.package,
          'signType': result.data.signType,
          'paySign': result.data.paySign,
          'success': function (res) {
            console.log(res)
            help.msg('支付成功');
            setTimeout(function () {
              var url = '/pages/consultation/quiz/quiz?id=' + pay_id;
              help.goUrl(url);
            }, 1000)
          },
          fail: function (res) {
            console.log(res)
            if (res && res.errMsg == 'requestPayment:fail cancel') {
              help.msg('未完成支付')
            } else {
              help.msg('支付失败！' + (res ? res.errMsg : ''))
            }

          }
        })

      } else if (result.code == 1) {
        help.msg('登录已失效，正在重新登录...')
        // 重新检测登录状态
        login.getUserInfo(app);
      } else {
        help.msg(result.msg)
        return false;
      }


    }, function (res, that) {
      wx.hideLoading()
      console.log(res);
      help.msg('网络异常！')
    });

  },
  set_msg: function (e) {
    this.setData({
      msg: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadBaseData();
  },
  loadBaseData: function () {
    var that = this;
    //医生
    help.get(app.data.apiUrl + 'Yisheng/info', { token: app.data.userInfo ? app.data.userInfo.token : '', id: that.data.yisheng_id }, that, function (res, that) {
      var result = res.data;
      // console.log(result);
      if (result.code == 1) {
        that.setData({
          yisheng_data: result.data,
        })
      }

    });
  },


  // 上传图片
  chooseImg: function () {
    var that = this;
    var max_count = 5 - that.data.product_images.length;
    if (max_count <= 0) {
      help.msg('最多上传5张图片');
      return false;
    }
    wx.chooseImage({
      count: max_count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        wx.showLoading({
          title: '正在上传...',
        })
        console.log(tempFilePaths)
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.data.apiUrl + 'Common/upload',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              token: app.data.userInfo ? app.data.userInfo.token : '',
            },
            success: function (res) {
              var data = JSON.parse(res.data)
              console.log(data)
              that.data.product_images.push(data.data.url_all)
              // that.data.product_images = data.data.url_all
              console.log(that.data.product_images)
              that.setData({
                product_images: that.data.product_images
              })
            }
          })
        }
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      },
      fail: function () {
        that.tips('选取图片失败')
      }
    })
  },

  /**
   * 删除图片
   */
  delimg: function (e) {
    var that = this;
    var new_img = [];
    var i = 0;
    for (i in that.data.product_images) {
      if (that.data.product_images[i] != e.currentTarget.dataset.src) {
        new_img.push(that.data.product_images[i])
      }
    }
    that.setData({
      product_images: new_img
    })
  },





  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})